#include <sdl/sdl.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <shared_setup.h>
#include <chunks/GuacInput_key_setup.h>
#include "guacinput.h"

static int create_key(lua_State *L)
{
    *(int*)lua_newuserdata(L, sizeof(int)) = lua_tointeger(L,1);
    return 1;
}

static int raw_key_down(lua_State *L)
{
    int idx = *(int*)lua_touserdata(L,1);
    lua_pushboolean(L, SDL_GetKeyState(NULL)[idx]);
    return 1;
}

static int raw_key_struck(lua_State *L)
{
    int idx = *(int*)lua_touserdata(L,1);
    lua_pushboolean(L, keysDown[idx]);
    return 1;
}

static int raw_key_released(lua_State *L)
{
    int idx = *(int*)lua_touserdata(L,1);
    lua_pushboolean(L, keysUp[idx]);
    return 1;
}

static int raw_key_summary(lua_State *L)
{
    lua_pushfstring(L, "charcode: %d", *(int*)lua_touserdata(L,1));
    return 1;
}

static luaL_Reg raw_key_functions[] = {
    {"create_key", create_key},
    {"get_key_down", raw_key_down},
    {"get_key_struck", raw_key_struck},
    {"get_key_released", raw_key_released},
    {"get_key_summary", raw_key_summary},

    {"getmetatable", raw_getmetatable},
    {"setmetatable", raw_setmetatable},
    {"getfenv", raw_getfenv},
    {"setfenv", raw_setfenv},
    {NULL,NULL}
};

int luaopen_key(lua_State* L)
{
    lua_newtable(L);
    luaL_register(L, NULL, raw_key_functions);

    luaL_loadbuffer(L, chunk_GuacInput_key_setup, sizeof(chunk_GuacInput_key_setup), NULL);
    lua_insert(L,-2);
    lua_call(L,1,1);

    lua_pushvalue(L,-1);
    lua_setglobal(L,"key");

    return 1;
}
